<template>
    <view class="container">
        <!-- 搜索筛选区 -->
        <view class="filter-section">
            <view class="search-bar">
                <input type="text" v-model="searchKey" placeholder="搜索教师" @confirm="searchTeachers" />
                <view class="search-btn" @tap="searchTeachers">搜索</view>
            </view>
            
            <!-- 分类导航 -->
            <scroll-view class="subject-scroll" scroll-x show-scrollbar="false">
                <view class="subject-scroll-content">
                    <view class="subject-item" 
                          :class="{ active: activeSubject === '' }"
                          @tap="selectSubject('')">
                        <text>全部</text>
                    </view>
                    <!-- 小学科目 -->
                    <view class="grade-group" v-if="primarySubjects.length > 0">
                        <view class="subject-item" 
                              v-for="(item, index) in primarySubjects" 
                              :key="'primary-'+index"
                              :class="{ active: activeSubject === item.name }"
                              @tap="selectSubject(item.name)">
                            <text>{{ item.name }}</text>
                        </view>
                    </view>
                    <!-- 初中科目 -->
                    <view class="grade-group" v-if="middleSubjects.length > 0">
                        <view class="subject-item" 
                              v-for="(item, index) in middleSubjects" 
                              :key="'middle-'+index"
                              :class="{ active: activeSubject === item.name }"
                              @tap="selectSubject(item.name)">
                            <text>{{ item.name }}</text>
                        </view>
                    </view>
                    <!-- 高中科目 -->
                    <view class="grade-group" v-if="highSubjects.length > 0">
                        <view class="subject-item" 
                              v-for="(item, index) in highSubjects" 
                              :key="'high-'+index"
                              :class="{ active: activeSubject === item.name }"
                              @tap="selectSubject(item.name)">
                            <text>{{ item.name }}</text>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 教师列表 -->
        <scroll-view class="teacher-list" scroll-y @scrolltolower="loadMore">
            <view class="teacher-item" v-for="(teacher, index) in teachers" :key="index" @tap="viewTeacherDetail(teacher)">
                <image :src="teacher.avatar || 'http://101.200.154.121:19000/teacher-manage-static/static/default-avatar.png'" class="teacher-avatar" mode="aspectFill"></image>
                <view class="teacher-info">
                    <view class="teacher-header">
                        <text class="teacher-name">{{ teacher.name }}</text>
                        <text class="teacher-title">{{ teacher.title }}</text>
                    </view>
                    <view class="teacher-subjects">{{ teacher.subjectsText || getSubjectText(teacher.subjects) }}</view>
                    <view class="teacher-description">{{ teacher.description }}</view>
                    <view class="teacher-footer">
                        <view class="price">¥{{ teacher.price }}/小时</view>
                        <view class="contact-btn" @tap.stop="contactTeacher(teacher)">联系老师</view>
                    </view>
                </view>
            </view>
            <view class="loading-container" v-if="loading">
                <view class="loading-spinner"></view>
                <view class="loading-text">加载中...</view>
            </view>
            <view class="no-more" v-if="noMore && !loading && teachers.length > 0">没有更多了</view>
            <view class="empty-list" v-if="teachers.length === 0 && !loading">暂无教师数据</view>
        </scroll-view>
    </view>
</template>

<script>
import { teacherApi } from '@/api/teacher.js'

export default {
    data() {
        return {
            searchKey: '',
            activeSubject: '',
            // 默认科目列表
            subjects: [
                { id: 1, name: '小学语文', grade: 1 },
                { id: 2, name: '小学数学', grade: 1 },
                { id: 3, name: '小学英语', grade: 1 },
                { id: 4, name: '初中语文', grade: 2 },
                { id: 5, name: '初中数学', grade: 2 },
                { id: 6, name: '初中英语', grade: 2 },
                { id: 7, name: '初中物理', grade: 2 },
                { id: 8, name: '初中化学', grade: 2 },
                { id: 9, name: '初中生物', grade: 2 },
                { id: 13, name: '高中语文', grade: 3 },
                { id: 14, name: '高中数学', grade: 3 },
                { id: 15, name: '高中英语', grade: 3 },
                { id: 16, name: '高中物理', grade: 3 },
                { id: 17, name: '高中化学', grade: 3 },
                { id: 18, name: '高中生物', grade: 3 },
                { id: 19, name: '高中历史', grade: 3 },
                { id: 20, name: '高中地理', grade: 3 },
                { id: 21, name: '高中政治', grade: 3 }
            ],
            teachers: [],
            page: 1,
            loading: false,
            noMore: false,
            minTeachingAge: null,
            maxTeachingAge: null,
            isSearch: false
        }
    },
    computed: {
        // 小学科目
        primarySubjects() {
            return this.subjects.filter(item => item.grade === 1)
        },
        // 初中科目
        middleSubjects() {
            return this.subjects.filter(item => item.grade === 2)
        },
        // 高中科目
        highSubjects() {
            return this.subjects.filter(item => item.grade === 3)
        }
    },
    onLoad(options) {
        console.log('教师列表页面参数:', options)

        // 如果有科目参数，设置为当前选中的科目
        if (options && options.subject) {
            const subjectName = decodeURIComponent(options.subject)
            console.log('从首页传入的科目:', subjectName)
            this.activeSubject = subjectName
        }

        // 尝试从服务器获取科目数据，如果失败则使用默认数据
        this.loadSubjects()

        // 延迟加载教师数据，确保科目设置完成
        this.$nextTick(() => {
            this.loadTeachers()
        })
    },
    methods: {
        // 加载科目数据
        async loadSubjects() {
            try {
                const res = await teacherApi.getSubjects()
                if (res && res.data && res.data.length > 0) {
                    this.subjects = res.data
                    console.log('成功加载科目列表:', this.subjects);
                } else {
                    console.log('科目数据为空，使用默认列表');
                }
            } catch (error) {
                console.error('获取科目列表失败:', error)
                // 保持使用默认科目列表
            }
        },
        
        // 选择科目
        selectSubject(subject) {
            console.log('选择科目:', subject);
            this.activeSubject = subject;
            this.page = 1;
            this.teachers = [];
            this.noMore = false;
            this.isSearch = false; // 重置搜索状态
            
            // 立即搜索新的结果
            setTimeout(() => {
                // 检查科目筛选是否生效
                if (subject) {
                    console.log('按科目筛选教师:', subject);
                    // 使用高级搜索接口以确保更精确的筛选
                    this.searchTeachersBySubject(subject);
                } else {
                    console.log('加载全部教师');
            this.loadTeachers();
                }
            }, 100);
        },
        
        // 按科目搜索教师（专用方法）
        async searchTeachersBySubject(subject) {
            if (this.loading) return;
            
            this.loading = true;
            try {
                console.log('开始按科目搜索教师:', subject);
                const params = {
                    page: this.page,
                    size: 10,
                    subject: subject
                };
                
                // 确保科目参数存在
                console.log('搜索参数:', JSON.stringify(params));
                
                // 使用search接口确保更精确的筛选
                const res = await teacherApi.searchTeachers(params);
                
                if (res && res.data) {
                    const records = Array.isArray(res.data.records) ? res.data.records : [];
                    console.log(`按科目 ${subject} 搜索结果:`, records.length);
                    
                    if (records.length === 0) {
                        this.noMore = true;
                        uni.showToast({
                            title: '暂无符合条件的教师',
                            icon: 'none'
                        });
                    } else {
                        this.teachers = records;
                        this.page++;
                        
                        if (records.length < 10) {
                            this.noMore = true;
                        }
                    }
                }
            } catch (error) {
                console.error('按科目搜索教师异常:', error);
                uni.showToast({
                    title: error.message || '网络错误，请重试',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },

        // 加载教师列表
        async loadTeachers() {
            if (this.loading || this.noMore) return;
            
            this.loading = true;
            try {
                const params = {
                    page: this.page,
                    size: 10
                };
                
                // 只有当实际选择了科目（非全部）时，才添加subject参数
                if (this.activeSubject) {
                    params.subject = this.activeSubject;
                    console.log('按科目过滤:', this.activeSubject);
                }
                
                // 如果有搜索关键词，添加到参数中
                if (this.searchKey) {
                    params.keyword = this.searchKey;
                }
                
                console.log('请求参数:', params);
                const res = await teacherApi.getTeacherList(params);

                if (res && res.data) {
                    const records = Array.isArray(res.data.records) ? res.data.records : [];
                    
                    if (records.length === 0) {
                        this.noMore = true;
                        if (this.page === 1) {
                            uni.showToast({
                                title: '暂无符合条件的教师',
                                icon: 'none'
                            });
                        }
                    } else {
                        this.teachers = [...this.teachers, ...records];
                        this.page++;
                        
                        if (this.page > res.data.pages || records.length < 10) {
                            this.noMore = true;
                        }
                    }
                }
            } catch (error) {
                console.error('获取教师列表异常:', error);
                uni.showToast({
                    title: error.message || '网络错误，请重试',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },

        // 搜索教师
        async searchTeachers() {
            if (this.loading) return;
            
            this.page = 1;
            this.teachers = [];
            this.noMore = false;
            this.isSearch = true;
            
            this.loading = true;
            try {
                const params = {
                    page: this.page
                };
                
                if (this.activeSubject) {
                    params.subject = this.activeSubject;
                }
                
                if (this.searchKey) {
                    params.name = this.searchKey;
                }
                
                if (this.minTeachingAge !== null) {
                    params.minTeachingAge = this.minTeachingAge;
                }
                
                if (this.maxTeachingAge !== null) {
                    params.maxTeachingAge = this.maxTeachingAge;
                }
                
                const res = await teacherApi.searchTeachers(params);

                if (res && res.data) {
                    const records = Array.isArray(res.data.records) ? res.data.records : [];
                    
                    if (records.length === 0) {
                        this.noMore = true;
                        uni.showToast({
                            title: '没有找到符合条件的教师',
                            icon: 'none'
                        });
                    } else {
                        this.teachers = records;
                        this.page++;
                        
                        if (records.length < 10) {
                            this.noMore = true;
                        }
                    }
                }
            } catch (error) {
                console.error('搜索教师异常:', error);
                uni.showToast({
                    title: error.message || '网络错误，请重试',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        
        // 加载更多
        loadMore() {
            if (this.isSearch) {
                this.loadMoreSearchResults();
            } else {
                this.loadTeachers();
            }
        },
        
        // 加载更多搜索结果
        async loadMoreSearchResults() {
            if (this.loading || this.noMore) return;
            
            this.loading = true;
            try {
                const params = {
                    page: this.page,
                    size: 10
                };
                
                // 只有当实际选择了科目（非全部）时，才添加subject参数
                if (this.activeSubject) {
                    params.subject = this.activeSubject;
                }
                
                // 如果有搜索关键词，添加到参数中
                if (this.searchKey) {
                    params.name = this.searchKey;
                }
                
                if (this.minTeachingAge !== null) {
                    params.minTeachingAge = this.minTeachingAge;
                }
                
                if (this.maxTeachingAge !== null) {
                    params.maxTeachingAge = this.maxTeachingAge;
                }
                
                console.log('搜索更多参数:', params);
                const res = await teacherApi.searchTeachers(params);
                
                if (res && res.data) {
                    const records = Array.isArray(res.data.records) ? res.data.records : [];
                    
                    if (records.length === 0) {
                        this.noMore = true;
                    } else {
                        this.teachers = [...this.teachers, ...records];
                        this.page++;
                        
                        if (records.length < 10) {
                            this.noMore = true;
                        }
                    }
                }
            } catch (error) {
                console.error('加载更多搜索结果异常:', error);
                uni.showToast({
                    title: error.message || '网络错误，请重试',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },

        // 查看教师详情
        viewTeacherDetail(teacher) {
            // 构建URL，包含手机号参数（如果存在）
            let url = `/pages/teacher/detail?id=${teacher.id}`;
            if (teacher.certification && teacher.certification.phone) {
                url += `&phone=${encodeURIComponent(teacher.certification.phone)}`;
            }

            uni.navigateTo({
                url: url,
                success: (res) => {
                    console.log('导航到教师详情页成功', res);
                },
                fail: (err) => {
                    console.error('导航到教师详情页失败', err);
                    // 尝试重定向到课程详情页作为备选
                    uni.navigateTo({
                        url: `/pages/course/detail?id=${teacher.id}`,
                        success: (res) => {
                            console.log('重定向到课程详情页成功', res);
                        },
                        fail: (errInner) => {
                            console.error('重定向也失败了', errInner);
                            uni.showToast({
                                title: '页面跳转失败',
                                icon: 'none'
                            });
                        }
                    });
                }
            });
        },
        
        // 联系老师
        contactTeacher(teacher) {
            // 构建URL，包含手机号参数
            let url = `/pages/teacher/detail?id=${teacher.id}`;
            if (teacher.certification && teacher.certification.phone) {
                url += `&phone=${encodeURIComponent(teacher.certification.phone)}`;
            }

            uni.navigateTo({
                url: url,
                success: (res) => {
                    console.log('导航到教师详情页成功', res);
                },
                fail: (err) => {
                    console.error('导航到教师详情页失败', err);
                    // 尝试重定向到课程详情页作为备选
                    uni.navigateTo({
                        url: `/pages/course/detail?id=${teacher.id}`,
                        success: (res) => {
                            console.log('重定向到课程详情页成功', res);
                        },
                        fail: (errInner) => {
                            console.error('重定向也失败了', errInner);
                            uni.showToast({
                                title: '页面跳转失败',
                                icon: 'none'
                            });
                        }
                    });
                }
            });
        },
        
        // 获取科目显示文本
        getSubjectText(subjects) {
            if (!subjects || subjects.length === 0) return '暂无科目信息';
            return subjects.join('、');
        },
        
        // 获取教师职称显示
        getTeacherTitle(teacher) {
            if (!teacher.teachingAge) return '教师';
            
            if (teacher.teachingAge >= 15) {
                return '高级教师';
            } else if (teacher.teachingAge >= 8) {
                return '一级教师';
            } else {
                return '教师';
            }
        }
    }
}
</script>

<style>
.container {
    padding: 20rpx;
    background: #f5f5f5;
}

.filter-section {
    position: sticky;
    top: 0;
    z-index: 100;
    background: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
}

.search-bar {
    background: #f5f5f5;
    padding: 20rpx;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
}

.search-bar input {
    font-size: 28rpx;
    flex: 1;
}

.search-btn {
    background: #E02E24;
    color: #fff;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    font-size: 26rpx;
    margin-left: 20rpx;
}

/* 拼多多风格横向滚动导航 */
.subject-scroll {
    width: 100%;
    white-space: nowrap;
}

.subject-scroll-content {
    display: flex;
    padding: 10rpx 0;
}

/* 添加分组样式 */
.grade-group {
    display: inline-flex;
    margin-right: 20rpx;
    position: relative;
}

.grade-group:not(:last-child)::after {
    content: '';
    position: absolute;
    right: -10rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 1px;
    height: 30rpx;
    background-color: #eee;
}

/* 修改科目项样式 */
.subject-item {
    display: inline-block;
    padding: 15rpx 30rpx;
    margin-right: 15rpx;
    border-radius: 8rpx;
    background-color: #f5f5f5;
    min-width: 120rpx;
    text-align: center;
    flex-shrink: 0;
    transition: all 0.3s ease;
}

.subject-item text {
    font-size: 26rpx;
    color: #333;
}

.subject-item.active {
    background-color: #FFF0EF;
    transform: scale(1.05);
}

.subject-item.active text {
    color: #E02E24;
    font-weight: bold;
}

.teacher-list {
    height: calc(100vh - 240rpx);
}

.teacher-item {
    display: flex;
    padding: 30rpx;
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    transition: transform 0.2s ease;
}

.teacher-item:active {
    transform: scale(0.98);
}

.teacher-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    margin-right: 20rpx;
    border: 2rpx solid #f5f5f5;
}

.teacher-info {
    flex: 1;
}

.teacher-header {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;
}

.teacher-name {
    font-size: 33rpx;
    font-weight: bold;
    margin-right: 20rpx;
	color: #999;
}

.teacher-title {
    font-size: 24rpx;
    color: #666;
    background: #f5f5f5;
    padding: 4rpx 16rpx;
    border-radius: 20rpx;
}

.teacher-subjects {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 10rpx;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
}

.teacher-description {
    font-size: 26rpx;
    color: #999;
    margin-bottom: 20rpx;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.teacher-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.price {
    color: #E02E24;
    font-size: 32rpx;
    font-weight: bold;
}

.contact-btn {
    background: #E02E24;
    color: #fff;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    font-size: 26rpx;
}

.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx;
    height: 100rpx;
}

.loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #E02E24;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.loading-text {
    margin-left: 20rpx;
    font-size: 26rpx;
    color: #666;
}

.no-more, .empty-list {
    text-align: center;
    padding: 30rpx;
    color: #999;
    font-size: 26rpx;
}

.empty-list {
    padding: 100rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.empty-list:before {
    content: "";
    display: block;
    width: 100rpx;
    height: 100rpx;
    background-image: url('data:image/svg+xml;utf8,<svg t="1628480626542" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7122"><path d="M512 454.4c-31.6 0-57.6 26-57.6 57.6v192c0 31.6 26 57.6 57.6 57.6s57.6-26 57.6-57.6V512c0-31.6-26-57.6-57.6-57.6z" fill="#cccccc" p-id="7123"></path><path d="M512 768m-57.6 0a57.6 57.6 0 1 0 115.2 0 57.6 57.6 0 1 0-115.2 0Z" fill="#cccccc" p-id="7124"></path><path d="M512 115.2c-219.2 0-396.8 177.6-396.8 396.8s177.6 396.8 396.8 396.8 396.8-177.6 396.8-396.8-177.6-396.8-396.8-396.8z m0 729.6c-182.4 0-332.8-150.4-332.8-332.8s150.4-332.8 332.8-332.8 332.8 150.4 332.8 332.8-150.4 332.8-332.8 332.8z" fill="#cccccc" p-id="7125"></path></svg>');
    background-size: contain;
    margin-bottom: 20rpx;
    opacity: 0.5;
}
</style> 